package lion.workflow;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import lion.dev.lang.MapJ;

import org.apache.commons.lang.StringUtils;

/**
 * 工作流动作定义
 *
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年7月22日
 */
public class WorkFlowTransition {

	private String name;
	private String to;
	private List<Condition> conditions;
	private int threshold = 0;
	private boolean rollback;

	public WorkFlowTransition(MapJ attribute, List<MapJ> cons) {

		this.name = attribute.getString("name");
		this.to = attribute.getString("to");
		this.threshold = attribute.getInt("threshold", 0);
		this.rollback = attribute.getBoolean("rollback");

		if (cons != null && !cons.isEmpty()) {
			this.conditions = new ArrayList<>();
			for (MapJ mapJ : cons) {

				Condition condition = new Condition(mapJ.getString("express"), mapJ.getString("to"));
				if (StringUtils.isBlank(condition.getTo())) {
					continue;
				}
				if (StringUtils.isBlank(condition.getExpress())) {
					this.to = condition.getTo();
					continue;
				}
				this.conditions.add(condition);
			}
		}
	}

	public int getThreshold() {

		return this.threshold;
	}

	public String getName() {

		return this.name;
	}

	public boolean isRollback() {

		return this.rollback;
	}

	// 变量处理
	// TODO
	public String getTo() {

		// if (this.conditions.isEmpty()) { return this.to; }
		// for (Condition condition : this.conditions) {
		// if (condition.matches(context)) { return condition.getTo(); }
		// }
		return this.to;
	}

	class Condition {

		private String express;
		private String to;
		private Random random = new Random();

		public Condition(String express, String to) {

			this.express = express;
			this.to = to;
		}

		public boolean matches(WorkflowContext context) {

			// TODO
			return this.random.nextBoolean();
		}

		public String getExpress() {

			return this.express;
		}

		public String getTo() {

			return this.to;
		}

	}

	public String findToState(WorkflowContext workflowContext) {

		// TODO Auto-generated method stub
		return null;
	}
}
